package org.web2024.dao;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class UserdetailsImp implements UserDetails {
    private User user;
    private List<String>permission;

    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public UserdetailsImp(User user) {
        this.user = user;
        char c=user.getUser_no().charAt(2);
        List<String> p = new ArrayList<>();
        if(c=='1')
            p.add("student");
        if(c=='2')
            p.add("teacher");
        if(c=='3')
            p.add("admin");
        this.permission=p;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        authorities = permission.stream().
                map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;

    }

    @Override
    public String getPassword() {
        return user.getUser_psw();
    }

    @Override
    public String getUsername() {
        return user.getUser_no();
    }

    /**
     * 判断账户是否未过期
     *
     * 重写自UserDetails接口，用于验证账户是否处于非过期状态
     *
     * @return 如果账户未过期，则返回true；否则返回false
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 判断账户是否未被锁定
     *
     * 重写自UserDetails接口，用于验证账户是否处于非锁定状态
     *
     * @return 如果账户未被锁定，则返回true；否则返回false
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 判断账户凭证是否未过期
     *
     * 重写自UserDetails接口，用于验证账户凭证是否处于非过期状态
     *
     * @return 如果账户凭证未过期，则返回true；否则返回false
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 判断账户是否启用
     *
     * 重写自UserDetails接口，用于验证账户是否处于启用状态
     *
     * @return 如果账户已启用，则返回true；否则返回false
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
